package com.senyint.imsdk.http;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.jivesoftware.smack.util.StringUtils;

public class AsyncHttpHandler {
	private static final long DEPLAY_CHECK = 3000L ;
	private Vector<SimpleHttpRequest> receivedPacketQueue = new Vector<SimpleHttpRequest>();
	private boolean isProcessRcvQueue = false ;
	private ExecutorService receiveExecutorService = null ;
	private Map<String,String> cacheMap = new ConcurrentHashMap<String,String>(); //记录所有json的请求,以防多次请求,文件请求不包括在内

	private Timer timer=new Timer();//实例化Timer类   
	
	private static AsyncHttpHandler instance = null ;
	public static AsyncHttpHandler getInstance(){
		if(instance == null){
			instance = new AsyncHttpHandler();
		}
		return instance ;
	}
	
	public AsyncHttpHandler(){
		final String threadId = "SHR-"+StringUtils.randomString(6);
		receiveExecutorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
					@Override
					public Thread newThread(Runnable runnable) {
						Thread thread = new Thread(
								runnable,
								"Simple Http Request Thread for Reveiving  " + threadId );
						thread.setPriority(Thread.MIN_PRIORITY);
						thread.setDaemon(true);
						return thread;
					}
				});
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				startPacketQueueProcess();
			}
		}, 1000); 
	}
	
	public void process(SimpleHttpRequest packet) {
		receivedPacketQueue.add(packet);
	}
	

	private void startPacketQueueProcess() {
		int cacheSize = receivedPacketQueue.size();
		if(!isProcessRcvQueue){
			isProcessRcvQueue = true ;
			receiveExecutorService.execute(new Runnable(){
				@Override
				public void run() {
					int size = 0 ;
					while ((size = receivedPacketQueue.size()) > 0 ) {
						SimpleHttpRequest request = receivedPacketQueue.firstElement();
						onProcessInBackgroud(request);
						receivedPacketQueue.remove(request);

						if(size == 1 ){
							isProcessRcvQueue = false ;
							break;
						}

						try {
							Thread.sleep(30L);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
		
	}

	/**
	 * 在安全线程中处理http<br>
	 * @param message
     */
	public void onProcessInBackgroud(SimpleHttpRequest request) {
		ISimpleHttpService  simpleHttp = null;
		
		switch(request.getRequestType()){
			case SimpleHttpRequest.REQUEST_GET:
				simpleHttp = createSimpleHttpService();
				simpleHttp.get(request.getUrl(), request.getParameter(), request.getCallback());
					break;
			case SimpleHttpRequest.REQUEST_POST:
				simpleHttp = createSimpleHttpService();
				simpleHttp.post(request.getUrl(), request.getParameter(), request.getCallback());
					break;
			case SimpleHttpRequest.REQUEST_UPLOAD:
				simpleHttp = createSimpleHttpService();
				simpleHttp.upload(request.getUrl(), request.getParameter(), request.getFiles(),request.getCallback());
					break;
			case SimpleHttpRequest.REQUEST_DOWN:
				simpleHttp = createSimpleHttpService();
				simpleHttp.download(request.getUrl(), request.getDestFile(),request.getCallback());
					break;
		}
		
	}
	
	public ISimpleHttpService createSimpleHttpService(){
		return new SimpleHttp();
	}
	
	public boolean contain(SimpleHttpRequest request){
		if(cacheMap.containsKey(request.getFlag())){
			return true ;
		}
		return false ;
	}
	
	public void shutdown(){
		receiveExecutorService.shutdown();
		receivedPacketQueue.removeAllElements();
	}

}
